# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymongo
import redis


class MyScrapyPipeline:
    def open_spider(self, spider):
        self.client = pymongo.MongoClient("mongodb://localhost:27017/")
        self.db = self.client.get_database("data")
        self.collection = self.db.get_collection("666")
        self.items = []

    def process_item1(self, item, spider):
        if spider.name == "quotes_all":
            print(spider.name, "77777777777777777", item)
            self.items.append(item)
            if len(self.items) == 10:
                self.collection.insert_many(self.items)
                self.items.clear()

        return item

    def close_spider(self, spider):
        if self.items:
            self.collection.insert_many(self.items)
            self.items.clear()
        self.client.close()


class RedisPipeline:
    def open_spider(self, spider):
        self.client = redis.Redis()
        self.client.delete("tasks")

    def process_item(self, item, spider):
        print("sssssss", item)
        self.client.lpush(
            "tasks",
            json.dumps(
                {
                    "url": "https://example.com",
                    "meta": {
                        "job-id": "123xsd",
                        "start-date": "dd/mm/yy",
                    },
                    "data": item,
                    "method": "POST",
                },
                ensure_ascii=False,
            ),
        )
        return item

    def close_spider(self, spider):

        self.client.close()
